package com.calm.cthreadpool;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Create by Calm
 * on 2019/8/12
 */
public class CFixedThreadPool extends AppCompatActivity {
    private final static String TAG = CFixedThreadPool.class.getSimpleName();
    private TextView tv;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cfixedthreadpool);
        tv = findViewById(R.id.tv);
        findViewById(R.id.start).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startTheadPool();
            }
        });
    }
    private void startTheadPool(){
        //通过Executors.newFixedThreadPool(N)创建的线程有N条固定数量线程的线程池，仅有核心线程且没有超时策略，线程不会被回收。
        //该方法创建的线程池没有非核心线程  当超过N数量的线程会等待前面线程执行完才会执行
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        for (int i = 0; i < 10; i++){
            final int index = i;
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                     Log.e(TAG,"CFixedThreadPool Start Run: 任务 = "+index+",线程 = "+Thread.currentThread().getName());
                    try {
                        Thread.sleep(2000);
                    }catch (InterruptedException e){

                    }
                }
            };
            executorService.execute(runnable);
        }
    }
}
